package com.bionic.banking.servlet;

import com.bionic.banking.core.entity.Customer;
import com.bionic.banking.logic.DomainUtil;
import com.bionic.banking.logic.controller.CustomerController;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class ImageServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        try {
            byte[] bytearray = null;
            String photoFile = (String) request.getParameter("photoFile");
            if (photoFile != null) {
                bytearray = DomainUtil.fileToByteArray(photoFile);
            } else {
                Integer id = Integer.valueOf(request.getParameter("customerId"));
                Customer customer = new CustomerController().getDetails(id);
                bytearray = customer.getImage();
            }
            if (bytearray != null) {

                response.setContentType("image/jpeg");               
                response.setContentLength(bytearray.length);
                if (response != null) {
                    BufferedImage myImage = ImageIO.read(new ByteArrayInputStream(bytearray));
                    ImageIO.write(myImage, "jpg", response.getOutputStream());
                    response.getOutputStream().flush();
                    response.getOutputStream().close();
                }
            }
        } catch (InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}